package com.ellecity06.cwhiskymall.ui.live.chat

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import com.ellecity06.common.base.BaseDialogFragment
import com.ellecity06.common.helper.ClickHelper
import com.ellecity06.common.helper.livemessage.LiveMessageRecyclerHelper
import com.ellecity06.common.ktx.load
import com.ellecity06.common.ktx.prefixUnit
import com.ellecity06.common.ktx.registerSoftInputChangedListener
import com.ellecity06.common.ktx.unregisterSoftInputChangedListener
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.LiveRoomMessageAdapter
import com.ellecity06.cwhiskymall.bean.LiveRoomMessageModel
import com.ellecity06.cwhiskymall.bean.response.LiveRoomGoodResponse
import com.ellecity06.cwhiskymall.databinding.FragmentDialogChatBinding
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import com.ellecity06.cwhiskymall.view.dialog.BackDialog

/**
 * @author ellecity06
 * @time 2024/11/29 14:30
 * @des
 */
class ChatDialogFragment : BaseDialogFragment<FragmentDialogChatBinding>(),
    LiveMessageRecyclerHelper.LiveMessageRecyclerHelperListener<LiveRoomMessageModel>, View.OnClickListener {
    private val chatAdapter: LiveRoomMessageAdapter by lazy { LiveRoomMessageAdapter(::onItemViewAttached) }

    private fun onItemViewAttached(adapterPosition: Int) {
        liveMessageRecyclerHelper.onAdapterItemViewAttached(adapterPosition)
    }

    private val liveMessageRecyclerHelper: LiveMessageRecyclerHelper<LiveRoomMessageModel> by lazy {
        LiveMessageRecyclerHelper(
            requireActivity()
        )
    }

    companion object {
        fun newInstance(): ChatDialogFragment {
            val fragment = ChatDialogFragment()
            return fragment
        }
    }

    fun setGoodList(list: List<LiveRoomGoodResponse>?) {
//        if (list.isNullOrEmpty()) {
//            return
//        }
        val instanse = LiveGoodDialog.newInstance()
        instanse.setGoodList(list)
        instanse.show(childFragmentManager, "LiveGoodDialog")
    }

    private var onChatClickListener: OnChatClickListener? = null
    fun setListener(onChatClickListener: OnChatClickListener) {
        this.onChatClickListener = onChatClickListener
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setStyle(STYLE_NORMAL, R.style.ChatDialogStyle)

    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return BackDialog(requireActivity(), theme)
    }

    override fun onStart() {
        super.onStart()
        val window: Window? = dialog!!.window
        if (window != null) {
            window.setBackgroundDrawableResource(R.color.transparent)
            val windowParams: WindowManager.LayoutParams = window.attributes
            windowParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            windowParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
            windowParams.dimAmount = 0.0f
            windowParams.gravity = Gravity.BOTTOM
            windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
            window.attributes = windowParams
        }
    }

    override fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentDialogChatBinding {
        return FragmentDialogChatBinding.inflate(inflater, container, false)
    }

    override fun initialize() {
//        registerSoft()
        initChatRv()
        initEvent()
    }

    private fun initEvent() {
        binding.tvSend.setOnClickListener(this)
        binding.etComment.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                val content = v?.text?.trim().toString()
                sendComment(content)

            }
            true
        }
        binding.tvUnread.setOnClickListener(this)
        binding.ivClose.setOnClickListener(this)
        binding.ivCart.setOnClickListener(this)
        binding.clGood.setOnClickListener(this)
    }

    private fun initChatRv() {
//        binding.rvComment.layoutManager = LinearLayoutManager(requireActivity())
//        binding.rvComment.addLinearDecoration(size = R.dimen.dp_5)
//        binding.rvComment.adapter = chatAdapter
//        liveMessageRecyclerHelper.setRecyclerView(binding.rvComment)
//        liveMessageRecyclerHelper.setUnreadTipsView(binding.tvUnread)
//        chatAdapter.submitList(liveMessageRecyclerHelper.list)
//        liveMessageRecyclerHelper.messageRecyclerHelperListener = this
//        liveMessageRecyclerHelper.prepareAsyncParseSpannable(
//            LiveRoomMessageModel(
//                "系统聊天",
//                "欢迎来到酒大G数字酒行~直播间严禁未成年人 打赏，直播间内严禁出现违法违规、低俗色情 人身伤害等内容。和谐健康的直播环境需要大 家一起呵护！！",
//            )
//        )

    }

    private fun registerSoft() {
        dialog?.window?.registerSoftInputChangedListener {
            logD("height=$it")
            if (it <= 0) {
                // 键盘属于消失状态
                showShareLayout()
            } else {
                // 键盘属于显示状态
                showSendBtn()

            }
        }
    }

    private fun showSendBtn() {
        binding.tvSend.visibility = View.VISIBLE
        binding.layoutShare.visibility = View.GONE
    }

    private fun showShareLayout() {
        binding.tvSend.visibility = View.GONE
        binding.layoutShare.visibility = View.VISIBLE
    }


    override fun onDestroy() {
        super.onDestroy()
        dialog?.window?.unregisterSoftInputChangedListener()
    }

    override fun unreadMessageCountUpdate(unreadCount: Int) {
        binding.tvUnread.text = "还有" + unreadCount + "条未读"
    }

    override fun asyncParseSpannableString(model: LiveRoomMessageModel) {

    }

    private fun sendComment(content: String?) {
        if (content.isNullOrEmpty()) {
            ToastUtils.show("请输入评论内容")
            return
        }
        logD("发送评论：$content")
        liveMessageRecyclerHelper.prepareAsyncParseSpannable(LiveRoomMessageModel("ZavierUp", content))
        binding.etComment.setText("")
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            binding.tvSend.id -> {
                // 发送消息
                val content = binding.etComment.text?.trim().toString()
                sendComment(content)
            }

            binding.tvUnread.id -> {
                liveMessageRecyclerHelper.scrollToBottom()
                v.visibility = View.GONE
            }

            binding.ivClose.id -> {
                requireActivity().onBackPressed()
            }

            binding.ivCart.id -> {
                ClickHelper.debounceClick {
                    onChatClickListener?.onGoodsClick()
                }

            }

            binding.clGood.id -> {
                ClickHelper.debounceClick {
                    topGood?.let {
                        WebHelper.goodDetails(requireActivity(), it.goodId,1)
                    }

                }
            }
        }
    }

    private var topGood: LiveRoomGoodResponse? = null
    fun onLiveStop(){
        binding.clGood.visibility = View.GONE
        binding.clComment.visibility = View.GONE
    }

    // 以下供外部调用
    fun showTopGood(good: LiveRoomGoodResponse?) {
        if (good != null) {
            binding.ivGoodsIcon.load(requireActivity(), good.mainProductImage)
            binding.tvGoodsName.text = good.productName
            binding.tvExchangeMoney.text = "赠送${good.contribution ?: 0.00}贡献金"
            binding.tvPrice.text = good.marketPrice?.prefixUnit()
            binding.clGood.visibility = View.VISIBLE
//        binding.clHot.visibility = View.VISIBLE
//        AnimeUtils.numberChangeAnimation(binding.tvHotSellNumber, 0F, 1024F, 2000,0).start()
            topGood = good
        } else {
            binding.clGood.visibility = View.GONE
        }

    }

    fun hideTopGood() {
        binding.clGood.visibility = View.INVISIBLE
    }
}